import { AppDataSource } from "@/config/database";
import { Customer } from "@/entities/basis/customer.entity";
import { ErrorHandler } from "@/middlewares/error.middleware";
import { TokenPayload } from "@/utils/token.util";
import { Context } from "koa";
import { Not } from "typeorm";

export interface IBody extends Customer { }

/** 更新客户信息 */
export async function updateCustomer(ctx: Context) {
    const updateData = ctx.request.body as IBody;
    const user: TokenPayload = ctx.state.user;
    const { id } = updateData

    if (!id) {
        throw new ErrorHandler('客户ID不能为空', 400);
    }

    const customerRepository = AppDataSource.getRepository(Customer);

    // 检查客户是否存在
    const customer = await customerRepository.findOne({
        where: { id: id as any }
    });

    if (!customer) {
        throw new ErrorHandler('客户不存在', 404);
    }

    // 验证手机号格式（如果提供了手机号）
    if (updateData.phone) {
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(updateData.phone)) {
            throw new ErrorHandler('手机号格式不正确', 400);
        }

        // 检查手机号是否已被其他客户使用
        const existingPhone = await customerRepository.findOne({
            where: { phone: updateData.phone, id: Not(id as any) }
        });
        if (existingPhone) {
            throw new ErrorHandler('手机号已被其他客户使用', 409);
        }
    }

    // 检查邮箱是否已被其他客户使用（如果提供了邮箱）
    if (updateData.email) {
        const existingEmail = await customerRepository.findOne({
            where: { email: updateData.email, id: Not(id as any) }
        });

        if (existingEmail) {
            throw new ErrorHandler('邮箱已被其他客户使用', 409);
        }
    }

    // 更新客户信息
    Object.assign(customer, { ...updateData, updatedBy: user.id });
    const updatedCustomer = await customerRepository.save(customer);

    ctx.body = updatedCustomer;
} 